package com.example.server.handle;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;

@Slf4j
public class MyWebSocketHandler implements WebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        log.info("客户端连接成功，sessionId: {}", webSocketSession.getId());

        SessionCache.add(webSocketSession);
    }

    @Override
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
        log.info("收到客户端发来的消息，sessionId: {}, message: {}", webSocketSession.getId(), webSocketMessage.getPayload());
        webSocketSession.sendMessage(new TextMessage("你好，你发的消息我已收到，你的原消息为：" + webSocketMessage.getPayload()));
    }

    @Override
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        log.error("发生错误,session id:{}", webSocketSession.getId());
        throwable.printStackTrace();

        SessionCache.remove(webSocketSession.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        log.info("客户端已断开，sessionId: {}", webSocketSession.getId());

        SessionCache.remove(webSocketSession.getId());
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}

